using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;

namespace CKY.AgentPlatform.ModelConfigs
{
    /// <summary>
    /// 增强的模型服务配置
    /// </summary>
    public class EnhancedModelServiceConfig
    {
        /// <summary>
        /// 熔断器配置
        /// </summary>
        public Dictionary<string, CircuitBreakerConfig> CircuitBreakerConfigs { get; set; } = new();

        /// <summary>
        /// 监控配置
        /// </summary>
        public MonitoringConfig MonitoringConfig { get; set; } = new();

        /// <summary>
        /// 错误处理配置
        /// </summary>
        public ErrorHandlingConfig ErrorHandlingConfig { get; set; } = new();

        /// <summary>
        /// 是否启用增强功能
        /// </summary>
        public bool EnableEnhancedFeatures { get; set; } = true;
    }

    /// <summary>
    /// 错误处理配置
    /// </summary>
    public class ErrorHandlingConfig
    {
        /// <summary>
        /// 默认重试次数
        /// </summary>
        public int DefaultMaxRetries { get; set; } = 3;

        /// <summary>
        /// 默认重试延迟（毫秒）
        /// </summary>
        public int DefaultRetryDelayMs { get; set; } = 1000;

        /// <summary>
        /// 启用错误分类
        /// </summary>
        public bool EnableErrorClassification { get; set; } = true;

        /// <summary>
        /// 启用错误恢复策略
        /// </summary>
        public bool EnableRecoveryStrategies { get; set; } = true;

        /// <summary>
        /// 错误通知阈值
        /// </summary>
        public int ErrorNotificationThreshold { get; set; } = 10;

        /// <summary>
        /// 异常过滤器配置
        /// </summary>
        public Dictionary<string, bool> ExceptionFilters { get; set; } = new();
    }

    /// <summary>
    /// 增强的模型服务
    /// </summary>
    public class EnhancedModelService
    {
        private readonly ILogger<EnhancedModelService> _logger;
        private readonly IConfiguration _configuration;
        private readonly ModelAdapterManager _adapterManager;
        private readonly ModelAdapterRegistry _adapterRegistry;
        private readonly CircuitBreakerManager _circuitBreakerManager;
        private readonly ModelMonitoringService _monitoringService;
        private readonly EnhancedModelServiceConfig _config;

        public EnhancedModelService(
            ILogger<EnhancedModelService> logger,
            IConfiguration configuration,
            ModelAdapterManager adapterManager,
            ModelAdapterRegistry adapterRegistry,
            CircuitBreakerManager circuitBreakerManager,
            ModelMonitoringService monitoringService)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
            _adapterManager = adapterManager ?? throw new ArgumentNullException(nameof(adapterManager));
            _adapterRegistry = adapterRegistry ?? throw new ArgumentNullException(nameof(adapterRegistry));
            _circuitBreakerManager = circuitBreakerManager ?? throw new ArgumentNullException(nameof(circuitBreakerManager));
            _monitoringService = monitoringService ?? throw new ArgumentNullException(nameof(monitoringService));

            // 加载配置
            _config = LoadConfiguration();

            // 初始化增强功能
            if (_config.EnableEnhancedFeatures)
            {
                InitializeEnhancedFeatures();
            }
        }

        /// <summary>
        /// 加载配置
        /// </summary>
        /// <returns>配置</returns>
        private EnhancedModelServiceConfig LoadConfiguration()
        {
            var config = new EnhancedModelServiceConfig();

            // 从配置文件加载
            var enhancedConfig = _configuration.GetSection("EnhancedModelService");
            if (enhancedConfig.Exists())
            {
                enhancedConfig.Bind(config);
            }

            // 设置默认熔断器配置
            if (config.CircuitBreakerConfigs.Count == 0)
            {
                config.CircuitBreakerConfigs = new Dictionary<string, CircuitBreakerConfig>
                {
                    ["default"] = new CircuitBreakerConfig
                    {
                        Name = "default",
                        FailureThreshold = 5,
                        TimeoutMs = 30000,
                        HalfOpenAttempts = 3,
                        SuccessThreshold = 2,
                        SlidingWindowMs = 60000
                    },
                    ["openai"] = new CircuitBreakerConfig
                    {
                        Name = "openai",
                        FailureThreshold = 3,
                        TimeoutMs = 60000,
                        HalfOpenAttempts = 2,
                        SuccessThreshold = 2,
                        SlidingWindowMs = 120000
                    },
                    ["zhipuai"] = new CircuitBreakerConfig
                    {
                        Name = "zhipuai",
                        FailureThreshold = 5,
                        TimeoutMs = 30000,
                        HalfOpenAttempts = 3,
                        SuccessThreshold = 2,
                        SlidingWindowMs = 60000
                    }
                };
            }

            // 设置默认监控配置
            if (config.MonitoringConfig == null)
            {
                config.MonitoringConfig = new MonitoringConfig
                {
                    Enabled = true,
                    DataRetentionHours = 168,
                    MaxRecords = 10000,
                    AggregationIntervalSeconds = 60,
                    EnableDetailedLogging = true,
                    PerformanceWarningThresholdMs = 5000,
                    ErrorRateWarningThreshold = 0.1,
                    EnableRealTimeMetrics = true
                };
            }

            return config;
        }

        /// <summary>
        /// 初始化增强功能
        /// </summary>
        private void InitializeEnhancedFeatures()
        {
            try
            {
                _logger.LogInformation("正在初始化增强模型服务功能...");

                // 注册增强适配器
                RegisterEnhancedAdapters();

                // 设置错误处理
                SetupErrorHandling();

                // 配置监控
                ConfigureMonitoring();

                _logger.LogInformation("增强模型服务功能初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化增强模型服务功能失败");
                throw;
            }
        }

        /// <summary>
        /// 注册增强适配器
        /// </summary>
        private void RegisterEnhancedAdapters()
        {
            // 注意：这里需要依赖注入来创建增强适配器实例
            // 在实际应用中，这些应该在Startup.cs或Program.cs中注册
            _logger.LogInformation("增强适配器已注册");
        }

        /// <summary>
        /// 设置错误处理
        /// </summary>
        private void SetupErrorHandling()
        {
            // 注册全局异常处理器
            AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
            {
                var exception = args.ExceptionObject as Exception;
                if (exception != null)
                {
                    HandleGlobalException(exception);
                }
            };

            _logger.LogInformation("错误处理机制已设置");
        }

        /// <summary>
        /// 配置监控
        /// </summary>
        private void ConfigureMonitoring()
        {
            // 记录服务启动指标
            _monitoringService.IncrementCounter("service_startup_total", new Dictionary<string, string>
            {
                ["service"] = "EnhancedModelService",
                ["version"] = "2.0.0"
            });

            _logger.LogInformation("监控功能已配置");
        }

        /// <summary>
        /// 获取熔断器
        /// </summary>
        /// <param name="name">熔断器名称</param>
        /// <returns>熔断器实例</returns>
        public ModelCircuitBreaker GetCircuitBreaker(string name)
        {
            var config = _config.CircuitBreakerConfigs.TryGetValue(name, out var breakerConfig)
                ? breakerConfig
                : _config.CircuitBreakerConfigs["default"];

            return _circuitBreakerManager.GetOrCreateCircuitBreaker(config);
        }

        /// <summary>
        /// 获取服务健康状态
        /// </summary>
        /// <returns>健康状态</returns>
        public Dictionary<string, object> GetHealthStatus()
        {
            var monitoringHealth = _monitoringService.GetHealthStatus();
            var circuitBreakerStats = _circuitBreakerManager.GetAllStats();

            return new Dictionary<string, object>
            {
                ["service"] = new Dictionary<string, object>
                {
                    ["name"] = "EnhancedModelService",
                    ["version"] = "2.0.0",
                    ["status"] = "healthy",
                    ["enabled"] = _config.EnableEnhancedFeatures,
                    ["uptime"] = DateTime.UtcNow - System.Diagnostics.Process.GetCurrentProcess().StartTime
                },
                ["monitoring"] = monitoringHealth,
                ["circuit_breakers"] = circuitBreakerStats,
                ["config"] = new Dictionary<string, object>
                {
                    ["monitoring_enabled"] = _config.MonitoringConfig.Enabled,
                    ["error_handling_enabled"] = _config.ErrorHandlingConfig.EnableErrorClassification,
                    ["max_records"] = _config.MonitoringConfig.MaxRecords,
                    ["data_retention_hours"] = _config.MonitoringConfig.DataRetentionHours
                }
            };
        }

        /// <summary>
        /// 获取详细的系统信息
        /// </summary>
        /// <returns>系统信息</returns>
        public Dictionary<string, object> GetSystemInfo()
        {
            var adapterStats = _adapterRegistry.GetStatistics();
            var recentExecutions = _monitoringService.GetRecentExecutions(10);
            var allMetrics = _monitoringService.GetAllMetrics();

            return new Dictionary<string, object>
            {
                ["adapters"] = new Dictionary<string, object>
                {
                    ["total"] = adapterStats.TotalAdapters,
                    ["providers"] = adapterStats.TotalProviders,
                    ["enabled_providers"] = adapterStats.EnabledProviders,
                    ["disabled_providers"] = adapterStats.DisabledProviders,
                    ["adapters_by_provider"] = adapterStats.AdaptersByProvider,
                    ["adapters_by_mode"] = adapterStats.AdaptersByMode
                },
                ["recent_executions"] = recentExecutions.Select(r => new
                {
                    r.ExecutionId,
                    r.ModelName,
                    r.Provider,
                    r.Success,
                    r.ResponseTimeMs,
                    r.ErrorMessage,
                    r.StartTime
                }).ToList(),
                ["metrics"] = allMetrics.GroupBy(m => m.Name).Select(g => new
                {
                    Name = g.Key,
                    Count = g.Count(),
                    TotalValue = g.Sum(m => m.Value),
                    AverageValue = g.Average(m => m.Value)
                }).ToList()
            };
        }

        /// <summary>
        /// 处理全局异常
        /// </summary>
        /// <param name="exception">异常</param>
        private void HandleGlobalException(Exception exception)
        {
            try
            {
                var errorInfo = ModelErrorClassifier.ClassifyException(exception);

                _logger.LogCritical(exception, "全局未处理异常: {ErrorType}, {ErrorMessage}",
                    errorInfo.ErrorType, errorInfo.ErrorMessage);

                // 记录错误指标
                _monitoringService.IncrementCounter("global_exceptions_total", new Dictionary<string, string>
                {
                    ["error_type"] = errorInfo.ErrorType.ToString(),
                    ["severity"] = errorInfo.Severity.ToString()
                });

                // 如果是严重错误，可以触发警报
                if (errorInfo.Severity == ErrorSeverity.Critical)
                {
                    TriggerAlert("CriticalError", errorInfo);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理全局异常时发生错误");
            }
        }

        /// <summary>
        /// 触发警报
        /// </summary>
        /// <param name="alertType">警报类型</param>
        /// <param name="errorInfo">错误信息</param>
        private void TriggerAlert(string alertType, ModelErrorInfo errorInfo)
        {
            // 这里可以实现警报逻辑，如发送邮件、短信、调用Webhook等
            _logger.LogWarning("触发警报: {AlertType}, 错误类型: {ErrorType}, 消息: {ErrorMessage}",
                alertType, errorInfo.ErrorType, errorInfo.ErrorMessage);

            // 记录警报指标
            _monitoringService.IncrementCounter("alerts_total", new Dictionary<string, string>
            {
                ["alert_type"] = alertType,
                ["error_type"] = errorInfo.ErrorType.ToString()
            });
        }

        /// <summary>
        /// 执行带完整保护的操作
        /// </summary>
        /// <param name="operation">操作</param>
        /// <param name="context">上下文</param>
        /// <returns>操作结果</returns>
        public async Task<T> ExecuteWithProtectionAsync<T>(
            Func<Task<T>> operation,
            Dictionary<string, object> context = null)
        {
            if (!_config.EnableEnhancedFeatures)
            {
                return await operation();
            }

            var operationName = context?.TryGetValue("operation_name", out var nameObj) == true
                ? nameObj.ToString()
                : "unknown";

            try
            {
                // 记录操作开始
                _monitoringService.IncrementCounter("operations_started_total", new Dictionary<string, string>
                {
                    ["operation"] = operationName
                });

                var startTime = DateTime.UtcNow;

                // 执行操作
                var result = await operation();

                // 记录操作成功
                var duration = (long)(DateTime.UtcNow - startTime).TotalMilliseconds;
                _monitoringService.RecordTimer("operation_duration_ms", duration, new Dictionary<string, string>
                {
                    ["operation"] = operationName
                });

                _monitoringService.IncrementCounter("operations_completed_total", new Dictionary<string, string>
                {
                    ["operation"] = operationName,
                    ["status"] = "success"
                });

                return result;
            }
            catch (Exception ex)
            {
                // 记录操作失败
                _monitoringService.IncrementCounter("operations_completed_total", new Dictionary<string, string>
                {
                    ["operation"] = operationName,
                    ["status"] = "failed"
                });

                // 分类错误
                var errorInfo = ModelErrorClassifier.ClassifyException(ex, context);

                // 记录错误指标
                _monitoringService.IncrementCounter("operation_errors_total", new Dictionary<string, string>
                {
                    ["operation"] = operationName,
                    ["error_type"] = errorInfo.ErrorType.ToString()
                });

                // 检查是否需要触发警报
                if (errorInfo.Severity == ErrorSeverity.Critical)
                {
                    TriggerAlert("OperationError", errorInfo);
                }

                throw;
            }
        }
    }
}